############################################
# Copyright (c) 2018 
#
# Written by 
############################################
import sys
import time
import logging

class pplog:
    DEBUG = logging.DEBUG
    INFO = logging.INFO
    WARN = logging.WARNING
    ERROR = logging.ERROR

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fmt = "%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s"

    logger = logging.getLogger('PP')
    logger.propagate = False
    logger.setLevel(logging.DEBUG)

    stdout = logging.StreamHandler()
    logger.addHandler(stdout)
    stdout.setFormatter(formatter)
    stdout.setLevel(logging.ERROR)

    logfile = None
    logfile_loglevel = logging.INFO

    @staticmethod
    def _conv_log_level(loglevel):
        lvls = {'debug'  :logging.DEBUG,
                'info'   :logging.INFO,
                'warning':logging.WARNING,
                'error'  :logging.ERROR}

        if loglevel in lvls:
            loglevel = lvls[loglevel]
        else:
            loglevel = int(loglevel)

        return loglevel

    @staticmethod
    def set_log_level(loglevel):
        loglevel = pplog._conv_log_level(loglevel)
        pplog.logfile_loglevel = loglevel
        if pplog.logfile:
            pplog.logfile.setLevel(loglevel)

    @staticmethod
    def enable_log(logfile):
        fh = logging.FileHandler(logfile, mode='w')
        fh.setLevel(pplog.logfile_loglevel)
        pplog.logger.addHandler(fh)
        fh.setFormatter(pplog.formatter)
        pplog.logfile = fh

    @staticmethod
    def set_print_level(lvl='ERROR'):
        lvl = pplog._conv_log_level(lvl)
        pplog.stdout.setLevel(lvl)

def pp_log(lvl=logging.DEBUG, *arg):
    pplog.logger.log(lvl, *arg)

def __pack_str(args):
    s = ''
    for a in args:
        s += str(a) + ' '
    return s

def pp_error(*arg):
    pp_log(logging.ERROR, __pack_str(arg))

def pp_warn(*arg):
    pp_log(logging.WARNING, __pack_str(arg))

def pp_info(*arg):
    pp_log(logging.INFO, __pack_str(arg))

def pp_debug(*arg):
    pp_log(logging.DEBUG, __pack_str(arg))

pp_print = pp_info

if __name__ == '__main__':
    pp_print('pp_print should not appear')
    pp_info('pp_info should not appera info%d', 1)
    pp_warn('pp_warn should not appera info%d', 1)
    pp_error('pp_error should appear')
    pplog.set_print_level('info')
    pp_info('pp_info should appera info%d', 1)
    pp_debug('pp_debug should not appera info%d', 1)

    pplog.enable_log('pp.log')
    pp_log(10, 'log shuld not appear')
    pplog.set_log_level(logging.DEBUG)
    pp_log(10, 'log should appear')
